package com.yunduansing.demo.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yunduansing.demo.exception.MyException;
import com.yunduansing.demo.model.common.ResponseModel;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
public class HttpErrorController implements ErrorController{

    private final static String ERROR_PATH = "/error";

    @ResponseBody
    @RequestMapping(path  = ERROR_PATH )
    @ExceptionHandler(value = {Exception.class})
    public ResponseModel error(HttpServletRequest request, HttpServletResponse response,Exception e){
        log.info(request.getRequestURI() + "  错误代码："  + response.getStatus()+" 错误信息："+e.getMessage());
        switch(response.getStatus()){
            case 401:
                return ResponseModel.error(response.getStatus(),"Unauthorized.");
            case 403:
                return ResponseModel.error(response.getStatus(),"权限不足。");
            case 404:
                return ResponseModel.error(response.getStatus(),"Page not found.");
            default:
                break;
        }
        //自定义异常才直接返给前端，否则只显示错误
        if(e instanceof MyException) {
            return ResponseModel.error(response.getStatus(),e.getMessage());
        }
        var result=ResponseModel.error(response.getStatus(),"出错了，请联系管理员。");
        return result;
    }

    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }
    
}